package com.example.mybaiduweishi.services;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.example.mybaiduweishi.MyApplication;
import com.example.mybaiduweishi.R;
import com.example.mybaiduweishi.activity.UpdateActivity;
import com.example.mybaiduweishi.utils.MyUtil;
import com.example.mybaiduweishi.utils.ToastUtil;
import com.socks.library.KLog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;

public class MyLoadNewVersionService extends Service {

    private static int id = 0;
    //创建通知栏
    static NotificationCompat.Builder    notificationBuild;
    //发送通知
    static NotificationManager notificationManager;

    public MyLoadNewVersionService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    //重写
    @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
        String url = null;
        if (intent != null)
        {
            url = intent.getStringExtra("apkurl");
        }
        CreateNotification();
        //下载，1、判断sd卡是否存在，存在即获取
        File file = MyUtil.getPath();
        //url:akp的地址、 file : 存放在手机中的位置
        downloadFile(url,file);
        return super.onStartCommand(intent, flags, startId);

    }
    //下载
    private void downloadFile(final String url, final File file) {
        //        url="http://localhost:8080/mobileDemo/apk/bdsjws-debug.apk";
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new FileCallBack(file.getAbsolutePath(),"bdws.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }
                    @Override
                    public void onResponse(File response, int id) {
                        notificationBuild.setContentText("下载完成");
                        notificationBuild.setAutoCancel(true);
                        notificationManager.notify(id, notificationBuild.build());
                        //调用安装的方法安装
                        anzhuang(response);
                        //点击通知栏
//                        Intent intent =anzhuang(response);
//                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(MyLoadNewVersionService.this);
//                        stackBuilder.addParentStack(UpdateActivity.class);
//                        stackBuilder.addNextIntent(intent);
//                        PendingIntent result = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_CANCEL_CURRENT);
//                        notificationBuild.setContentIntent(result);
//                        //让进度条消失
//                        notificationBuild.setProgress(0,0,false);
//                        //可以在方法中设置自动安装
//                        notificationBuild.setContentText("请点击安装");
//                        notificationBuild.setContentTitle("下载完成");
//                        notificationManager.notify(id,notificationBuild.build());

                    }
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
//                        KLog.i("===================",progress);
//                        notificationBuild.setProgress(100,(int)(progress*100),true);
//                        notificationBuild.setContentText("已经下载了"+(int)(progress*100)+"%");
////                        Toast.makeText(MyApplication.getContext(), "下载完成", Toast.LENGTH_SHORT).show();
//                        ToastUtil.showShortToast(MyApplication.getContext(),"下载完成");
//                        notificationManager.notify(id,notificationBuild.build());
                        notificationBuild.setContentText("已经下载了"+(int)(progress*100)+"%");
                        notificationBuild.setProgress(100, (int) (progress * 100),false);
                        ToastUtil.showShortToast(MyApplication.getContext(),"下载完成");
                        notificationManager.notify(id,notificationBuild.build());


                    }
                });
    }

    //安装APK
    private static void anzhuang(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        MyApplication.getContext().startActivity(intent);
//        return intent;
    }

    //创建通知栏
    public static void CreateNotification(){
        notificationManager = (NotificationManager) MyApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationBuild = new NotificationCompat.Builder(MyApplication.getContext());
        notificationBuild.setContentTitle("我的卫士……")
                .setContentText("准备下载……")
                .setSmallIcon(R.drawable.ic_logo)
                .setOngoing(true) //设置他为一个正在进行的通知
                .setTicker("更新手机卫士！！！")
//                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true);
        notificationManager.notify(id, notificationBuild.build());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
